from flask import Flask, render_template, request
import os
from dotenv import load_dotenv
import logging
# 从milvus_utils模块导入ensure_milvus_connection
from milvus_utils import ensure_milvus_connection
from services.doc_service import handle_doc_upload, handle_doc_search
from services.image_service import handle_image_upload, handle_image_search

load_dotenv()
ensure_milvus_connection()

logging.basicConfig(
    level=logging.DEBUG,  # 设置日志级别
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)

logger = logging.getLogger(__name__)

def create_app():
    app = Flask(__name__)

    # 定义路由的视图函数
    @app.route("/")
    def home():
        logger.info("访问首页")
        return render_template("home.html", title="AI智能检索首页")

    # 定义上传文档路由"/upload_doc", 支持GET和POST方法
    @app.route("/upload_doc", methods=["GET", "POST"])
    def upload_doc():
        return handle_doc_upload(request)

    # 定义搜索文档路由"/search_doc", 支持GET和POST方法
    @app.route("/search_doc", methods=["GET", "POST"])
    def search_doc():
        return handle_doc_search(request)

    # 定义搜索文档路由"/upload_image", 支持GET和POST方法
    @app.route("/upload_image", methods=["GET", "POST"])
    def upload_image():
        return handle_image_upload(request)

    # 定义搜索文档路由"/upload_image", 支持GET和POST方法
    @app.route("/search_image", methods=["GET", "POST"])
    def search_image():
        return handle_image_search(request)

    return app

if __name__ == "__main__":
    # 创建应用
    app = create_app()
    # 设置应用的密钥，用于会话加密，从环境变量中获取
    app.secret_key = os.getenv("SECRET_KEY")
    app.run(debug=True)


